﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CMS.Utils;
using CMS.BL.Entity;
using CMS.Services;


namespace CMS.UI.Controllers
{
    public class BaseController : Controller
    {
        private tbl_Domains _domain;
        private readonly IDomain DomainService;

        public BaseController(IDomain domainService)
        {
            this.DomainService = domainService;
        }

        protected virtual CustomPrincipal AdminUser
        {
            get { return HttpContext.User as CustomPrincipal; }
        }

        protected int DomainID
        {
            get
            {
                if (Request == null || Request.Url.Host.Contains("localhost") || Request.Url.Host.Contains("10.0.2.2")) 
                    return 1;

                if (this._domain != null)
                    return this._domain.DomainID;
                else
                {
                    this._domain = DomainService.GetDomainByName(Request.Url.Host);
                    if (this._domain != null && this._domain.DO_Domain != Request.Url.Host)
                        Response.RedirectPermanent(new UriBuilder(Request.Url.Scheme, this._domain.DO_Domain, Request.Url.Port, Request.Url.AbsolutePath).ToString());

                    return this._domain != null ? this._domain.DomainID : 0;
                }
            }
        }

        protected tbl_Domains Domain
        {
            get
            {
                if (Request == null)
                    return null;

                if (this._domain == null)
                {
                    this._domain = DomainService.GetDomainByID(DomainID);
                }

                return this._domain;
            }
        }


        protected void SendTweet(string message)
        {
            var domain = this.Domain;
            if (domain != null && domain.DO_UpdateTwitter && !String.IsNullOrEmpty(message))
            {
                TweetManager tweet = new TweetManager(domain.DO_TwitterToken, domain.DO_TwitterSecret, domain.DO_ConsumerKey, domain.DO_ConsumerSecret);
                tweet.SendTweet(message);
            }
        }
    }
}
